/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package at.irian.web.jsf.orchestra;

import org.apache.myfaces.orchestra.conversation.ConversationContext;
import org.apache.myfaces.orchestra.conversation.ConversationManager;

import javax.faces.component.UIViewRoot;

/**
 * @author Manfred Geiler
 */
class LastResponseHolder
{
    private static final String REQUEST_ATTRIBUTE_NAME = LastResponseHolder.class.getName();

    private UIViewRoot viewRoot = null;
    private String redirectUrl = null;

    public UIViewRoot getViewRoot()
    {
        return viewRoot;
    }

    public void setViewRoot(UIViewRoot viewRoot)
    {
        this.viewRoot = viewRoot;
        this.redirectUrl = null;
    }

    public String getRedirectUrl()
    {
        return redirectUrl;
    }

    public void setRedirectUrl(String redirectUrl)
    {
        this.redirectUrl = redirectUrl;
        this.viewRoot = null;
    }

    public boolean isRedirect()
    {
        return this.redirectUrl != null;
    }

    /**
     * @return may return null for get-requests of e.g. jsf2
     */
    public static LastResponseHolder getCurrentInstance()
    {
        ConversationManager manager = ConversationManager.getInstance();
        if (manager == null)
        {
            throw new IllegalStateException("No ConversationManager available");
        }
        ConversationContext conversationContext = manager.getCurrentConversationContext();
        if (conversationContext == null)
        {
            return null;
        }

        //noinspection SynchronizationOnLocalVariableOrMethodParameter
        synchronized (conversationContext)
        {
            LastResponseHolder lastResponseHolder = (LastResponseHolder) conversationContext.getAttribute(REQUEST_ATTRIBUTE_NAME);

            if (lastResponseHolder == null)
            {
                lastResponseHolder = new LastResponseHolder();
                conversationContext.setAttribute(REQUEST_ATTRIBUTE_NAME, lastResponseHolder);
            }
            return lastResponseHolder;
        }
    }
}
